package com.vxdata.utils.modules.utils.case_8x;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@ServerEndpoint("/adjustWebSocket/{username}")
@Slf4j
@Data
public class WebSocket {


    private static AtomicInteger onlineCount = new AtomicInteger(0);
    private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
    private Session session;
    private String username;

    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) throws IOException {
        this.username = username;
        this.session = session;
        WebSocket.onlineCount.incrementAndGet();
        clients.put(username, this);
        log.info("【AdjustWebSocket消息】有新的连接, 总数:{}", onlineCount);
    }

    @OnClose
    public void onClose() throws IOException {
        clients.remove(username);
        WebSocket.onlineCount.decrementAndGet();
        log.info("【AdjustWebSocket消息】连接断开, 总数:{}", onlineCount);
    }

    @OnMessage
    public void onMessage(String username) throws IOException {
        // 心跳
        for (WebSocket item : clients.values()) {
            if (item.username.equals(username))
                item.session.getAsyncRemote().sendText("pang");
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("【AdjustWebSocket】发生错误：{}", error);
        error.printStackTrace();
    }

    public void sendMessageTo(String message, String To) throws IOException {
        for (WebSocket item : clients.values()) {
            if (item.username.equals(To))
                item.session.getAsyncRemote().sendText(message);
        }
    }

    public void sendMessageAll(String message) throws IOException {
        for (WebSocket item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }

    public static synchronized Map<String, WebSocket> getClients() {
        return clients;
    }
}
